package com.qk.interceptor;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求路径
        String path = request.getRequestURI();
        //2.判断路径是否为登录路径
        if (path.contains("/login")){
            return  true;
        }

        //3.获取请求头中的token
        String token = request.getHeader("token");
        //4.判断token是否为空
        if (token == null){
            log.info("token为空");
            response.setStatus(401);
            return  false;
        }

        //5.解析token
        try {
            JwtUtils.parseToken(token);
            Integer userId = (Integer) JwtUtils.parseToken(token).get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(userId);
        }catch (Exception e){
            log.info("解析token异常",e);
            response.setStatus(401);
            return  false;
        }

        //6.放行
        return true;

    }

    private void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler) {
        CurrentUserHoler.removeCurrentUser();
    }
}
